package com.luoran.bartalks.utils;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * 
 * @author WMM
 *
 */
public class ChangeImageSizeUtil {

	/***
	 * @title 重置图片大小
	 * 
	 * @param srcFile  原图片
	 * 
	 * @param width    新的宽度
	 * 
	 * @param height   新的高度
	 * 
	 * @param destFile 转化后的图片
	 * 
	 */
	public static void resizeImage(File srcFile, File destFile) {

		try {
			BufferedImage sourceImg = ImageIO.read(new FileInputStream(srcFile));
			int width = sourceImg.getWidth(); // 源图宽度
			int height = sourceImg.getHeight(); // 源图高度

			if (!destFile.exists()) {
				destFile.createNewFile();
			}
			FileWriter fileWriter = new FileWriter(destFile);
			fileWriter.write("");
			fileWriter.flush();
			fileWriter.close();
			if (!destFile.getParentFile().exists())
				destFile.getParentFile().mkdirs();
			Image i = ImageIO.read(srcFile);
			i = resizeImage(i, (width / 2 < 600) ? width / 2 : 600, (height / 2 < 600) ? height / 2 : 600);
			ImageIO.write((RenderedImage) i, "jpg", destFile);
		} catch (IOException e) {
			System.out.println("文件不存在");
			e.printStackTrace();
		}
	}

	public static Image resizeImage(Image srcImage, int width, int height) {
		try {

			BufferedImage buffImg = null;
			buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			buffImg.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);

			return buffImg;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
